package com.tcpengine.net;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

// 编码 | 解码 器
public class Encoder {
	// 网络协议解码
	public final static Msg decode(ByteBuf byteBuf) {	// 仅测试使用，这里没有考虑连包网络情况
		System.out.println("网络协议解码...");
		if (byteBuf.readableBytes() < Msg.MSG_HEADER_LEN) {
			return null;
		}
		byteBuf.markReaderIndex();
		int id = byteBuf.readInt();
		int bodyLen = byteBuf.readInt();
		int is = byteBuf.readableBytes();
		if (byteBuf.readableBytes() < bodyLen) {	
			byteBuf.resetReaderIndex();
			return null;
		}
		ByteBuf body = Unpooled.buffer(bodyLen);
		byteBuf.readBytes(body);
		Msg msg = new Msg(id, bodyLen, body);
		return msg;
	}

	// 网络协议编码
	public final static ByteBuf encode(Msg msg) {
		System.out.println("网络数据编码...");
		if(1002 == msg.id) {
			System.out.println("编码id=1002消息...");
			int len = msg.bodyLen + Msg.MSG_HEADER_LEN + 2;
			ByteBuf buffer = Unpooled.buffer(len);
			buffer.writeInt(msg.id);
			buffer.writeInt(msg.bodyLen);
			buffer.writeShort(123);
			if(null != msg.body) {
				buffer.writeBytes(msg.body);
			}
			return buffer;
		}
		else {
			int len = msg.bodyLen + Msg.MSG_HEADER_LEN;
			ByteBuf buffer = Unpooled.buffer(len);
			buffer.writeInt(msg.id);
			buffer.writeInt(msg.bodyLen);
			if(null != msg.body) {
				buffer.writeBytes(msg.body);
			}
			return buffer;
		}
	}
}
